using Common;
using Entity;
using Newtonsoft.Json;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
using Utils;

namespace CardGameObject.GameScene
{
    public class GameCard : MonoBehaviour
    {
        public TextMeshPro AttackText;
        public TextMeshPro CostText;
        public TextMeshPro HealthText;
        public TextMeshPro NameText;
        public SpriteRenderer CardImage;
        public SpriteRenderer CardBack;
        public SpriteRenderer CardRare;

        public GameManager GameManager { get; set; }

        public PlayerRoleEnum CardRole { get; set; }

        public int HandIndex { get; set; }

        public CardStatusEnum CardStatus { get; set; } = CardStatusEnum.HAND;
        public long CardId { get; set; }

        public string CardName { get; set; }

        public int Attack { get; set; }

        public int Health { get; set; }

        public CardTypeEnum CardType { get; set; }

        public int Cost { get; set; }

        public CardRarityEnum CardRarity { get; set; }

        public int CurHealth { get; set; }

        public int CurAttack { get; set; }

        public int CurCost { get; set; }

        public Card Card { get; set; }

        public GameMonsterPosition GameMonsterPosition { get; set; }

        public string[] EffectWord { get; set; }

        public string EffectText { get; set; }

        public string[] NameWord { get; set; }

        public int AttackCountPerTurn { get; set; } = 0;
        
        #region 卡牌面板变化方法

        public void IncreaseAttack(int value)
        {
            CurAttack += value;
            UpdateText(AttackText, CurAttack, Attack);
        }

        public void IncreaseHealth(int value)
        {
            Health += value;
            CurHealth += value;
            UpdateText(HealthText , CurHealth, Health);
        }

        public void ReduceAttack(int value)
        {
            CurAttack = CurAttack - value < 0 ? 0 : CurAttack - value;
            UpdateText(AttackText, CurAttack, Attack);
        }

        public void TakeDamage(int value)
        {
            if(value <= 0)
            {
                return;
            }
            CurHealth = CurHealth - value < 0 ? 0 : CurHealth - value;
            LaunchMonsterEffect("DAMAGE");
            if(CurHealth == 0)
            {
                GameMonsterPosition.IsUsed = false;
                GameManager.DoDestroy(this);
                LaunchMonsterEffect("DESTROY");
                Destroy(gameObject);
            }
            else
            {
                UpdateText(HealthText, CurHealth, Health);
            }
        }

        public void Recover(int value)
        {
            CurHealth = CurHealth + value > Health ? Health : CurHealth + value;
            UpdateText(HealthText, CurHealth, Health);
        }

        public void RecoverToMax()
        {
            CurHealth = Health;
            UpdateText(HealthText, CurHealth, Health);
        }

        public void ChangeHealthToValue(int value)
        {
            CurHealth = value;
            Health = value;
            UpdateText(HealthText, CurHealth, Health);
        }

        public void ChangeAttackToValue(int value)
        {
            int originalAttack = Attack;
            CurAttack = value;
            Attack = value;
            UpdateText(AttackText, CurAttack, Attack);
        }

        public void ChangeCostToValue(int value)
        {
            Cost = value;
            CurCost = value;
            UpdateText(CostText, CurCost, Cost);
        }
    
        // 修改 UpdateText 方法
        private void UpdateText(TextMeshPro textMeshPro, int curValue, int originalValue)
        {
            textMeshPro.text = curValue.ToString();
            if (curValue > originalValue)
            {
                textMeshPro.color = Color.black;
            }
            else if (curValue < originalValue)
            {
                textMeshPro.color = Color.black;
            }
            else
            {
                textMeshPro.color = Color.black;
            }
        }
    
    
        #endregion

        private void Start()
        {
            GameManager = GameManager.GetInstance();
        }
        private void OnMouseDown()
        {
            if (EventSystem.current.IsPointerOverGameObject())
            {
                return;
            }
            GameManager.GameCardDisplay.SetCardInfo(this);
            // 如果在手牌中则执行召唤/发动操作
            if (CardStatus == CardStatusEnum.HAND)
            {
                if(CardType == CardTypeEnum.MONSTER_CARD)
                {
                    GameManager.CloseAttackBorder();
                    GameManager.ResetAttackProperties();
                    GameManager.ResetLaunchProperties();
                    GameManager.CurSummonMonster = this.gameObject;
                    GameManager.CurSummonMonsterRole = CardRole;
                    GameManager.CurSummonMonsterHandIndex = HandIndex;
                    GameManager.SetSummonPositionBorder();
                }
                else if(CardType == CardTypeEnum.SPELL_CARD)
                {
                    GameManager.CloseAttackBorder();
                    GameManager.ResetAttackProperties();
                    GameManager.CloseSummonBorder();
                    GameManager.ResetSummonProperties();
                    GameManager.CurLaunchRole = CardRole;
                    GameManager.CurLaunchSpell = this.gameObject;
                    GameManager.CurLaunchSpellHandIndex = HandIndex;
                }
                // 如果在场上则执行攻击或者被攻击操作
            }else if(CardStatus == CardStatusEnum.FIELD)
            {
                GameManager.CloseSummonBorder();
                GameManager.ResetSummonProperties();
                GameManager.ResetLaunchProperties();
                if(GameManager.CurAttackMonster == null)
                {
                    if(AttackCountPerTurn <= 0)
                    {
                        Debug.Log("出击次数不足");
                        return;
                    }
                    GameManager.CurAttackMonster = this.gameObject;
                    GameManager.CurAttackRole = CardRole;
                    GameManager.SetAttackPositionBorder();
                }
                else
                {
                    if(GameManager.CheckMonsterAttackable(this , CardRole))
                    {
                        GameManager.CurAttackMonsterTarget = this.gameObject;
                        GameManager.DoAttack();
                    }
                    else
                    {
                        GameManager.CloseAttackBorder();
                        GameManager.ResetAttackProperties();
                    }
                }
            }
        }

        public void SetCardInfo()
        {
            if (Card != null)
            {
                BeanUtil.CopyProperties(Card, this);
            }
            CurAttack = Attack;
            CurCost = Cost;
            CurHealth = Health;
            UpdateText(AttackText, CurAttack, Attack);
            UpdateText(CostText, CurCost, Cost);
            UpdateText(HealthText, CurHealth, Health);
            NameText.text = CardName;

            EffectWord = JsonConvert.DeserializeObject<string[]>(Card.EffectWord);
            NameWord = JsonConvert.DeserializeObject<string[]>(Card.NameWord);

            Sprite sprite = Resources.Load<Sprite>($"Images/CardImage/Content/{CardName}");
            if(sprite != null)
            {
                CardImage.sprite = sprite;
            }
    
            // 根据 cardRarity 属性的值更改 CardRare 对应的图像颜色
            switch (CardRarity)
            {
                case CardRarityEnum.N:
                    CardRare.color = Color.white;
                    break;
                case CardRarityEnum.R:
                    CardRare.color = Color.blue;
                    break;
                case CardRarityEnum.SR:
                    CardRare.color = new Color(1f, 0.84f, 0f); // 金黄色
                    break;
                case CardRarityEnum.UR:
                    CardRare.color = Color.red;
                    break;
                default:
                    Debug.LogWarning($"未处理的卡牌稀有度: {CardRarity}");
                    break;
            }
        }

        /// <summary>
        /// 召唤怪兽，将怪兽移动到场上
        /// </summary>
        /// <param name="monsterPosition">召唤怪兽的地点</param>
        public void SummonMonster(GameObject monsterPosition)
        {
            MoveUtil.SimpleMove(this.gameObject , monsterPosition);

            // 设置状态
            CardStatus = CardStatusEnum.FIELD;
            LaunchMonsterEffect("SUMMON");

            GameMonsterPosition = monsterPosition.GetComponent<GameMonsterPosition>();
        }

        /// <summary>
        /// 执行对怪兽的攻击，调用双方怪兽的TakeDamage方法计算伤害
        /// </summary>
        /// <param name="target">攻击目标</param>
        public void AttackMonster(GameCard target)
        {
            LaunchMonsterEffect("ATTACK");
            TakeDamage(target.CurAttack);
            target.TakeDamage(CurAttack);
            AttackCountPerTurn--;
            Debug.Log($"{CardName}攻击了{target.CardName}，自身受到了{target.CurAttack}点伤害，对方受到了{CurAttack}点伤害");
        }

        /// <summary>
        /// 执行对玩家的攻击，调用玩家的TakeDamage方法计算伤害
        /// </summary>
        /// <param name="targetPlayer">攻击目标玩家</param>
        public void AttackPlayer(GamePlayer targetPlayer)
        {
            LaunchMonsterEffect("ATTACK");
            targetPlayer.TakeDamage(CurAttack);
            AttackCountPerTurn--;
        }

        /// <summary>
        /// 发动法术效果
        /// 调用工具类方法进行效果发动
        /// </summary>
        public void LaunchSpellEffect()
        {
            LaunchEffectUtil.LaunchSpellEffect(this);
            GameManager.ResetLaunchProperties();
            GameManager.DoDestroy(this);
            Destroy(gameObject);
        }

        /// <summary>
        /// 发动怪兽效果
        /// 设置当前的发动怪兽，发动玩家
        /// 调用工具类的方法进行效果发动
        /// </summary>
        /// <param name="launchTime">发动时机</param>
        public void LaunchMonsterEffect(string launchTime)
        {
            GameManager.CurLaunchMonster = this.gameObject;
            GameManager.CurLaunchRole = CardRole;
            LaunchEffectUtil.LaunchMonsterEffect(this, launchTime);
            GameManager.ResetLaunchProperties();
        }

        public bool HasEffectWord(string word)
        {
            foreach (var effectWord in EffectWord)
            {
                if (effectWord.Equals(word))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
